package com.seer.auto.entity;

import com.seer.auto.entity.factory.MapEntityFactory;
import com.seer.auto.utils.ClassUtils;
import java.util.Map;
import javassist.CannotCompileException;
import javassist.NotFoundException;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

@Data
@ToString
public class MetaEntity<T> {

    private static final String packageName = "com.seer.auto.entity";
    private static final String factoryPackageName = "com.seer.auto.entity.factory";
    private Class<T> clazz;
    private Table table;
    private MapEntityFactory<T> factory;
    private String className;

    public MetaEntity(Table table, boolean init)
        throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException {
        this.table = table;
        this.className = ClassUtils.className(table.getName());
        if (init) {
            clazz = (Class<T>) ClassUtils.newEntity(
                StringUtils.joinWith(".", packageName, this.className),
                table);
            factory = (MapEntityFactory<T>) (ClassUtils.makeFactory(
                    StringUtils.joinWith(".", factoryPackageName, this.className + "Factory"), this)
                .newInstance());
        }
    }

    public T newInstance(Map<String, Object> params) {
        return factory.create(params);
    }


}
